package com.mama100.rpc.mdp.service.finagle;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.mama100.common.finagle.util.FinagleRPC;
import com.mama100.common.finagle.util.RpcUtil;
import com.mama100.rpc.mdp.MdpInoutUtil;
import com.mama100.rpc.mdp.thrift.inout.GetAggregateCommissionRequest;
import com.mama100.rpc.mdp.thrift.inout.GetAggregateCommissionResponse;
import com.mama100.rpc.mdp.thrift.inout.GetCommissionDetailByIdRequest;
import com.mama100.rpc.mdp.thrift.inout.GetCommissionDetailByIdResponse;
import com.mama100.rpc.mdp.thrift.inout.GetCommissionDetailsRequest;
import com.mama100.rpc.mdp.thrift.inout.GetCommissionDetailsResponse;
import com.mama100.rpc.mdp.thrift.inout.TCommission;
import com.mama100.rpc.mdp.thrift.inout.TCommissionDetail;
import com.mama100.rpc.mdp.thrift.inout.common.BaseResponse;
import com.twitter.util.ExecutorServiceFuturePool;
import com.twitter.util.Function0;
import com.twitter.util.Future;

@FinagleRPC
@Service("terminalCommissionService")
public class TerminalCommissionService  implements com.mama100.rpc.mdp.thrift.TerminalCommissionService.ServiceIface{

	protected Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ExecutorServiceFuturePool futurePool;
	
	@Resource(name = "crmJdbcTemplate")
	JdbcTemplate jdbcTemplate;
	
	@Override
	public Future<GetAggregateCommissionResponse> getAggregateCommission(GetAggregateCommissionRequest req) {
		return futurePool.apply(new Function0<GetAggregateCommissionResponse>() {
			@Override
			public GetAggregateCommissionResponse apply() {
				GetAggregateCommissionResponse resp = MdpInoutUtil.getGetAggregateCommissionResponse(RpcUtil.genSeqNo());
				BaseResponse base = resp.getBaseResp();
				if (req.getBaseReq().getSeqNo() != null) {
					base.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				try {
					//获取传参数据
					String terminalCode = req.getTerminalCode(); //门店编码
					Date startTime = new Date(req.getStartTime());  //开始时间
					Date endTime = new Date(req.getEndTime());  //结束时间
					
					RowMapper<TCommission> rowMapper = new RowMapper<TCommission>() {
						@Override
						public TCommission mapRow(ResultSet rs, int rowNum) throws SQLException {
							TCommission c = new TCommission();
							
							c.setPaidCommission(rs.getDouble("paidCommission"));
							c.setUnpaidCommission(rs.getDouble("unpaidCommission"));
							c.setTotalCommission(rs.getDouble("totalCommission"));
							return c;
						}
					};
					
					//查询
					String sql = "select sum(b.share_benefit_charge) totalCommission,sum(case when b.settle_status = 24 then b.share_benefit_charge end ) paidCommission,sum(case when b.settle_status = 23 then b.share_benefit_charge end ) unpaidCommission ";
					sql += " from mama100_owner.fss_brand_outlet_order b,mama100_owner.fss_outlet_transfer_money t ";
					sql += " where b.member_terminal_code=? ";
					sql += " and b.settle_status in (23,24) and b.order_status in (7,8) ";
					sql += " and t.created_time >=? and t.created_time < ? ";
					sql += " and t.terminal_code = b.member_terminal_code and t.settle_account_id = b.settle_account_id ";
					List<TCommission> value = jdbcTemplate.query(sql, new Object[] { terminalCode,startTime,endTime }, rowMapper);
					//组装返回结果
					resp.setValue(value.get(0));
				} catch (Exception e) {
					log.error("seqNo:"+req.getBaseReq().getSeqNo()+"--"+e.toString());
				}
				return resp;
			}

		});
	}

	@Override
	public Future<GetCommissionDetailsResponse> getCommissionDetails(GetCommissionDetailsRequest req) {
		return futurePool.apply(new Function0<GetCommissionDetailsResponse>() {
			@Override
			public GetCommissionDetailsResponse apply() {
				GetCommissionDetailsResponse resp = MdpInoutUtil.getGetCommissionDetailsResponse(RpcUtil.genSeqNo());
				BaseResponse base = resp.getBaseResp();
				if (req.getBaseReq().getSeqNo() != null) {
					base.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				try {
					
					//获取传参数据
					String terminalCode = req.getTerminalCode();
					Date startTime = new Date(req.getStartTime());  
					Date endTime = new Date(req.getEndTime());
					//结算状态
					int settleStatus = req.getSettleStatus();
					int firstResult = req.getFirstResult();
					int maxResult = req.getMaxResult();
					
					
					RowMapper<TCommissionDetail> rowMapper = new RowMapper<TCommissionDetail>() {
						@Override
						public TCommissionDetail mapRow(ResultSet rs, int rowNum) throws SQLException {
							TCommissionDetail t = new TCommissionDetail();
							t.setId(rs.getLong("id")); //记录标识
							t.setCustomerName(rs.getString("order_customer_name"));// 会员姓名
							t.setCommissionCharge(rs.getDouble("share_benefit_charge"));//收入或扣减金额
							t.setBankDesc(rs.getString("bank_of_deposit"));//开户行
							
							String bankCard = rs.getString("bank_card_number");
							if(bankCard != null && bankCard.length()>=4){
								t.setCardLast4(bankCard.substring(bankCard.length()-4, bankCard.length()));//卡号后4位
							}
							t.setOrderId(rs.getLong("order_cust_order_code"));//订单编号
							t.setTerminalName(rs.getString("terminal_name"));//  下单门店
							t.setOrderCharge(rs.getDouble("orderCharge"));//贷款金额
							
							Date orderTime = rs.getTimestamp("order_created_time");
							Date commissionTime = rs.getTimestamp("created_time");
							Date transferTime = rs.getTimestamp("transfer_time");
							if(orderTime != null){
								t.setOrderTime(orderTime.getTime());//下单时间
							}
							if(commissionTime != null){
								t.setCommissionTime(commissionTime.getTime());//   分佣时间
							}
							if(transferTime != null){
								t.setTransferTime(transferTime.getTime());// 结算或扣款时间
							}
							t.setSettleType(rs.getInt("settle_status"));// 结算类型
							t.setOrderType(rs.getInt("order_status"));//订单类型
							
							return t;
						}
					};
					
					//查询
					StringBuffer sb = new StringBuffer();
					if(firstResult >= 0 && maxResult > 0){
						sb.append(" select * from ( ");
					}
					sb.append(" select ");
					sb.append(" rownum as rowno, ");
					sb.append(" b.id, ");
					sb.append(" b.order_customer_name, ");
					sb.append(" b.share_benefit_charge, ");
					sb.append(" t.bank_of_deposit, ");
					sb.append(" t.bank_card_number, ");
					sb.append(" b.order_cust_order_code, ");
					sb.append(" b.terminal_name, ");
					sb.append(" (nvl(b.pay_total_amount, 0) - nvl(b.order_freight, 0)) orderCharge, ");
					sb.append(" b.order_created_time, ");
					sb.append(" t.created_time, ");
					sb.append(" t.transfer_time, ");
					sb.append(" b.settle_status, ");
					sb.append(" b.order_status ");
					sb.append(" from mama100_owner.fss_brand_outlet_order b,mama100_owner.fss_outlet_transfer_money t ");
					sb.append(" where b.member_terminal_code=? and b.order_status in (7,8)");
					
					if(settleStatus == 1){//已划款
						sb.append(" and b.settle_status = 24 ");
					}else if(settleStatus == 2){//未划款
						sb.append(" and b.settle_status = 23 ");
					}else{
						sb.append(" and b.settle_status in (23,24) ");
					}
					
					sb.append(" and t.created_time >=? and t.created_time < ? ");
					sb.append(" and t.terminal_code = b.member_terminal_code and t.settle_account_id = b.settle_account_id ");
					
					if(firstResult >= 0 && maxResult > 0){
						sb.append(" and rownum <= ? order by t.created_time desc ) ");
						sb.append(" where rowno > ? ");
					}else{
						sb.append(" order by t.created_time desc ");
					}
					//System.out.println(sb.toString());
					if(firstResult >= 0 && maxResult > 0){
						List<TCommissionDetail> value = jdbcTemplate.query(sb.toString(), new Object[] { terminalCode,startTime,endTime,firstResult+maxResult,firstResult }, rowMapper);
						//组装返回结果
						resp.setValue(value);
					}else{
						List<TCommissionDetail> value = jdbcTemplate.query(sb.toString(), new Object[] { terminalCode,startTime,endTime}, rowMapper);
						//组装返回结果
						resp.setValue(value);
					}
				} catch (Exception e) {
					log.error("seqNo:"+req.getBaseReq().getSeqNo()+"--"+e.toString());
				}
				return resp;
			}

		});
	}

	@Override
	public Future<GetCommissionDetailByIdResponse> getCommissionDetailById(GetCommissionDetailByIdRequest req) {
		return futurePool.apply(new Function0<GetCommissionDetailByIdResponse>() {
			@Override
			public GetCommissionDetailByIdResponse apply() {
				GetCommissionDetailByIdResponse resp = MdpInoutUtil.getGetCommissionDetailByIdResponse(RpcUtil.genSeqNo());
				BaseResponse base = resp.getBaseResp();
				if (req.getBaseReq().getSeqNo() != null) {
					base.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				try {
					//获取传参数据
					Long id = req.getId();
					
					RowMapper<TCommissionDetail> rowMapper = new RowMapper<TCommissionDetail>() {
						@Override
						public TCommissionDetail mapRow(ResultSet rs, int rowNum) throws SQLException {
							TCommissionDetail t = new TCommissionDetail();
							t.setId(rs.getLong("id")); //记录标识
							t.setCustomerName(rs.getString("order_customer_name"));// 会员姓名
							t.setCommissionCharge(rs.getDouble("share_benefit_charge"));//收入或扣减金额
							t.setBankDesc(rs.getString("bank_of_deposit"));//开户行
							
							String bankCard = rs.getString("bank_card_number");
							t.setCardLast4(bankCard.substring(bankCard.length()-4, bankCard.length()));//卡号后4位
							
							t.setOrderId(rs.getLong("order_cust_order_code"));//订单编号
							t.setTerminalName(rs.getString("terminal_name"));//  下单门店
							t.setOrderCharge(rs.getDouble("orderCharge"));//贷款金额
							
							Date orderTime = rs.getTimestamp("order_created_time");
							Date commissionTime = rs.getTimestamp("created_time");
							Date transferTime = rs.getTimestamp("transfer_time");
							if(orderTime != null){
								t.setOrderTime(orderTime.getTime());//下单时间
							}
							if(commissionTime != null){
								t.setCommissionTime(commissionTime.getTime());//   分佣时间
							}
							if(transferTime != null){
								t.setTransferTime(transferTime.getTime());// 结算或扣款时间
							}
							t.setSettleType(rs.getInt("settle_status"));// 结算类型
							t.setOrderType(rs.getInt("order_status"));//订单类型
							
							return t;
						}
					};
					//查询
					StringBuffer sb = new StringBuffer();
					sb.append(" select ");
					sb.append(" b.id, ");
					sb.append(" b.order_customer_name, ");
					sb.append(" b.share_benefit_charge, ");
					sb.append(" t.bank_of_deposit, ");
					sb.append(" t.bank_card_number, ");
					sb.append(" b.order_cust_order_code, ");
					sb.append(" b.terminal_name, ");
					sb.append(" (nvl(b.pay_total_amount, 0) - nvl(b.order_freight, 0)) orderCharge, ");
					sb.append(" b.order_created_time, ");
					sb.append(" t.created_time, ");
					sb.append(" t.transfer_time, ");
					sb.append(" b.settle_status, ");
					sb.append(" b.order_status ");
					sb.append(" from mama100_owner.fss_brand_outlet_order b,mama100_owner.fss_outlet_transfer_money t ");
					sb.append(" where b.id=? ");
					sb.append(" and t.terminal_code = b.member_terminal_code and t.settle_account_id = b.settle_account_id ");
					
					List<TCommissionDetail> value = jdbcTemplate.query(sb.toString(), new Object[] { id }, rowMapper);
					if(value != null && value.size()>0){
						resp.setValue(value.get(0));
					}
				} catch (Exception e) {
					log.error("seqNo:"+req.getBaseReq().getSeqNo()+"--"+e.toString());
				}
				//组装返回结果
				return resp;
			}

		});
	}
	
}
